{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 让openAI的api使用阿里云的服务器\n",
    "阿里百炼大模型API获取：https://bailian.console.aliyun.com/?apiKey=1#/api-key\n",
    "使用文档：https://help.aliyun.com/zh/model-studio/getting-started/what-is-model-studio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'我看到您的问题似乎有个小小的输入错误。我猜您想问的是\"今天是星期几\"。\\n\\n要准确回答这个问题，我需要知道\"今天\"的具体日期。建议您可以:\\n1. 查看手机或电脑的日历\\n2. 告诉我具体的日期\\n3. 使用系统时间询问\\n\\n我可以帮您确定具体的星期信息，只需要您提供更多细节。'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "import os\n",
    "os.environ['http_proxy'] = 'http://127.0.0.1:1084'\n",
    "os.environ['https_proxy'] = 'http://127.0.0.1:1084'\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=\"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\",  # 淘宝买的\n",
    "    base_url=\"https://api.anthropic.com/v1\" # claude\n",
    ")\n",
    "\n",
    "\n",
    "def llm(user_query):\n",
    "    system_prompt = f\"\"\"You are an expert at routing a user question to the relevant agent.Always replay in Chinese.\n",
    "    \"\"\"\n",
    "    query = user_query\n",
    "\n",
    "    completion = client.chat.completions.create(\n",
    "        # model=\"claude-3-7-sonnet-20250219\",\n",
    "        model=\"claude-3-5-haiku-20241022\",\n",
    "        messages=[{'role': 'system', 'content': system_prompt},\n",
    "                  {'role': 'user', 'content': query}],\n",
    "        )\n",
    "    return completion.choices[0].message.content\n",
    "\n",
    "#llm(\"你是哪个版本的模型\")\n",
    "llm(\"今天是3月20号，星期几\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用http request而非openai库来访问大模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是Claude 3 Opus，这是Anthropic推出的Claude 3系列中性能最高的版本。\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "# claude API 的配置信息\n",
    "api_key = \"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\"  # 替换为你的阿里云百炼大模型 API Key\n",
    "api_url = \"https://api.anthropic.com/v1/messages\"   # API 的完整路径\n",
    "\n",
    "def llm(user_query):\n",
    "    system_prompt = \"\"\"你会搜索网络，并给出答案.\"\"\"\n",
    "    query = user_query\n",
    "\n",
    "    # 构造请求的 payload\n",
    "    payload = {\n",
    "        \"model\": \"claude-3-7-sonnet-20250219\",\n",
    "        \"max_tokens\": 8192,\n",
    "        \"messages\": [\n",
    "           # {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": query}\n",
    "        ]\n",
    "    }\n",
    "\n",
    "    # 设置请求的 headers\n",
    "    headers = {\n",
    "        \"Content-Type\": \"application/json\",\n",
    "        \"anthropic-version\": \"2023-06-01\",\n",
    "        \"x-api-key\": f\"{api_key}\",\n",
    "    }\n",
    "\n",
    "    # 发送 POST 请求\n",
    "    response = requests.post(api_url, headers=headers, data=json.dumps(payload))\n",
    "\n",
    "    # 检查响应状态\n",
    "    if response.status_code != 200:\n",
    "        raise Exception(f\"HTTP error! status: {response.status_code}, response: {response.text}\")\n",
    "\n",
    "    # 解析响应内容\n",
    "    response_data = response.json()\n",
    "    return response_data[\"content\"][0][\"text\"]\n",
    "\n",
    "# 测试函数\n",
    "result = llm(\"你是claude哪个版本？\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 运行李继刚的提示词"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I'll analyze these logical propositions using the logical blade approach.\\n\\n```\\n┌─────────────────────────────────────────────────────────┐\\n│                                                         │\\n│                     逻辑之刃 🗡️                         │\\n│                                                         │\\n├─────────────────────────────────────────────────────────┤\\n│                                                         │\\n│  命题分析：                                             │\\n│  A: Post Training是工程而非算法问题                     │\\n│  B: 用户反馈决定训练效果                                │\\n│  C: 数据质量优于数据规模                                │\\n│                                                         │\\n│  逻辑关系：                                             │\\n│  1. 命题A将Post Training归类为工程问题，暗含            │\\n│     A→¬(Post Training是算法问题)                        │\\n│                                                         │\\n│  2. 命题B确立了因果关系：                               │\\n│     用户反馈→训练效果，这是一个充分条件关系             │\\n│                                                         │\\n│  3. 命题C确立了比较关系：                               │\\n│     数据质量>数据规模，表明在权衡取舍时的优先级         │\\n│                                                         │\\n│  推导链：                                               │\\n│  - 若A成立，则工程实践(如数据处理、反馈收集)            │\\n│    而非理论创新成为关键                                 │\\n│  - 若B成立，则优化用户反馈机制直接提升训练效果          │\\n│  - 若C成立，则资源应优先投入数据筛选而非盲目扩充        │\\n│                                                         │\\n│  整合推理：                                             │\\n│  A∧B∧C⇒高效训练应聚焦于工程化收集高质量用户反馈        │\\n│  数据，而非算法革新或简单扩大数据规模                   │\\n│                                                         │\\n│  本质洞见：                                             │\\n│  这三个命题共同指向一个实用主义的AI训练理念 —           │\\n│  在复杂理论之外，实践中的具体工程实现、用户导向         │\\n│  及精细化数据策略可能是模型优化的更高效路径。           │\\n│                                                         │\\n├─────────────────────────────────────────────────────────┤\\n│                       李继刚 2024                        │\\n└─────────────────────────────────────────────────────────┘\\n```\""
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "#import os\n",
    "#os.environ['http_proxy'] = 'http://127.0.0.1:1082'\n",
    "#os.environ['https_proxy'] = 'http://127.0.0.1:1082'\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=\"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\",  # 淘宝买的\n",
    "    base_url=\"https://api.anthropic.com/v1\" # claude\n",
    ")\n",
    "\n",
    "\n",
    "def llm(user_query):\n",
    "    system_prompt = f\"\"\"\n",
    "    ;; ━━━━━━━━━━━━━━\n",
    "    ;; 作者: 李继刚\n",
    "    ;; 版本: 0.4\n",
    "    ;; 模型: Claude Sonnet\n",
    "    ;; 用途: 使用逻辑之刃解读文本逻辑脉络\n",
    "    ;; ━━━━━━━━━━━━━━\n",
    "\n",
    "    ;; 设定如下内容为你的 *System Prompt*\n",
    "    (require 'dash)\n",
    "\n",
    "    (defun 逻辑学家 ()\n",
    "    \"擅长命题化、逻辑推理并清晰表达的逻辑学家\"\n",
    "    (list (经历 . '(求真务实 广博阅读 严谨治学 深度思考))\n",
    "            (技能 . '(命题化 符号化 推理 清晰阐述 论证构建 谬误识别))\n",
    "            (表达 . '(通俗易懂 简洁明了 精准有力 层次分明))))\n",
    "\n",
    "    (defun 逻辑之刃 (用户输入)\n",
    "    \"逻辑之刃, 庖丁解牛\"\n",
    "    (let* ((命题 \"可明确判定真与假的陈述句, 使用字母表示 [A,B,C]\")\n",
    "            (操作符 ((\"可针对命题进行操作, 形成新的逻辑表达式的符号\")\n",
    "                    (\"¬\" . \"非: 否定一个命题\")\n",
    "                    (\"∀\" . \"全称量词\")\n",
    "                    (\"∃\" . \"存在量词\")\n",
    "                    (\"→\" . \"充分条件: p→q 代表 p 是 q 的充分条件\")\n",
    "                    (\"∧\" . \"且: 当且仅当两个命题均为真时,该操作符的结果才为真\")))\n",
    "            (推理符 ((\"表达两个逻辑表达式之间的推导关系\")\n",
    "                    (\"⇒\" . \"一个表达可推导另一个表达式 [p⇒q]\")\n",
    "                    (\"⇔\" . \"两个表达式可互相推导 [p⇔q]\")))\n",
    "            (推理法则 ((\"双重否定律\" . \"¬¬p ⇔ p\")\n",
    "                        (\"对置律\" . \"(p → q) ⇔ (¬q → ¬p)\")\n",
    "                        (\"传递律\" . \"(p → q) ∧ (q → r) ⇒ (p → r)\")))\n",
    "            (推理方法\n",
    "            (list\n",
    "            (直接推理 . '(代入 换位 换质 扩大 限制))\n",
    "            (间接推理 . '(三段论 假言推理 选言推理))\n",
    "            (归纳推理 . '(完全归纳 不完全归纳))\n",
    "            (类比推理 . '(正向类比 反向类比 米田嵌入))))\n",
    "            (命题集 (-> 用户输入\n",
    "                        提取核心命题\n",
    "                        (形式化处理 操作符)\n",
    "                        字母命名命题))\n",
    "            (逻辑链 (-> 命题集\n",
    "                        (推理法则 推理符)\n",
    "                        (多维度推理 推理方法)\n",
    "                        逻辑推导链))\n",
    "            (本质 (-> 逻辑链\n",
    "                    背后原理 ;; 问题背后的问题, 现象背后的原理\n",
    "                    推导新洞见))\n",
    "            ;; 命题和符号推导, 均对应着通俗易懂的简洁自然语言\n",
    "            (响应 (简洁准确 (翻译为自然语言 命题集 逻辑链 本质))))\n",
    "        (生成卡片 用户输入 响应)))\n",
    "\n",
    "    (defun 生成卡片 (用户输入 响应)\n",
    "    \"生成优雅简洁的 SVG 卡片\"\n",
    "    (let ((画境 (-> `(:画布 (640 . 1024)\n",
    "                        :margin 30\n",
    "                        :配色 极简主义\n",
    "                        :排版 '(对齐 重复 对比 亲密性)\n",
    "                        :字体 (font-family \"KingHwa_OldSong\")\n",
    "                        :构图 (外边框线\n",
    "                            (标题 \"逻辑之刃 🗡️\") 分隔线\n",
    "                            (美化排版 响应)\n",
    "                            分隔线 \"李继刚 2024\"))\n",
    "                    元素生成)))\n",
    "        画境))\n",
    "\n",
    "    (defun start ()\n",
    "    \"逻辑学家, 启动!\"\n",
    "    (let (system-role (逻辑学家))\n",
    "        (print \"系统启动中, 逻辑之刃已就绪...\")))\n",
    "\n",
    "    ;; ━━━━━━━━━━━━━━\n",
    "    ;;; Attention: 运行规则!\n",
    "    ;; 1. 初次启动时必须只运行 (start) 函数\n",
    "    ;; 2. 接收用户输入之后, 调用主函数 (逻辑之刃 用户输入)\n",
    "    ;; 3. 严格按照(生成卡片) 进行排版输出\n",
    "    ;; 4. 输出完 SVG 后, 不再输出任何额外文本解释\n",
    "    ;; ━━━━━━━━━━━━━━\n",
    "    \"\"\"\n",
    "    query = user_query\n",
    "\n",
    "    completion = client.chat.completions.create(\n",
    "        model=\"claude-3-7-sonnet-20250219\",\n",
    "        messages=[{'role': 'system', 'content': system_prompt},\n",
    "                  {'role': 'user', 'content': query}],\n",
    "        )\n",
    "    return completion.choices[0].message.content\n",
    "\n",
    "query = \"\"\"\n",
    "A: Post Training是工程而非算法问题\n",
    "B：用户反馈决定训练效果\n",
    "C：数据质量优于数据规模\n",
    "\"\"\"\n",
    "llm(query)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
